import {Component, Inject, OnInit} from '@angular/core';
import {_HttpClient} from '@delon/theme';
import {recodeModule} from '../../../service/delivent/recodeModule';
import {UtilityService} from '../../../service/utils.service';
import {appConfig} from '../../../service/common';
import {NzModalService, NzNotificationService} from 'ng-zorro-antd';
import {Router} from '@angular/router';
import {DA_SERVICE_TOKEN, ITokenService} from '@delon/auth';
import * as moment from 'moment';

@Component({
    selector: 'app-ad-record',
    templateUrl: './ad-record.component.html',
})
export class AdRecordComponent implements OnInit {
    constructor(
        private http: _HttpClient,
        private router: Router,
        private utilityService: UtilityService,
        private modal: NzModalService,
        private nznot: NzNotificationService,
       @Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService,
    ) { }

    // 变量
    token: any;
    list: any[] = [];
    mergeId: any;
    showAdd: boolean; // 是否有修改
    configTitle = '详情';
    modalVisible = false;
    mergeVisible = false; // 合并投放弹窗
    isPagination = true; // 是否有分页
    // 信息
expandForm = false;
    deliveryTime: any; // 投放日期
    pageTotal: number;
    isShow = false;
    pageIndex = 1;
    YpageIndex = 1;
    YpageTotal :number;
    data: any[] = []; // 表格数据
    isShowTotalhead = true;
    test: string;
    page: any;
    total: number;
    listloading = false

    detailVisible= false;
    // 按钮点击事件
    idcheck: any
    checkloading: any;
    checkStatus: boolean;
    title: any;
    mergeListInfo: any[] = [];
    mergeListData: any[] = []; // 核查有异议的数据
    checkModalData: any[] = []; // 核查清单数据
    loading1 = false
    loading2 = false
    iStouchanRecord = false;
    guidprent=[];
    dliveryResult = [
        {key: '0', value: '否'},
        {key: '1', value: '是'}
    ]
    deliveryResults = appConfig.Enumeration.deliveryResults;
    headerDate = [  // 配置表头内容
        { label: '别名', value: 'checkAlias', isclick: true },
        { label: '核查时间', value: 'checkDate', isclick: false },
        { label: '核查状态', value: 'checkStatus', isclick: false },
        { label: '核查人', value: 'checkUser', isclick: false },
        { label: '运行环境', value: 'guidProfiles', isclick: false },
        { label: '打包窗口', value: 'packTiming', isclick: false },
    ];
    checkStatusGroup = [
           {label:'核对作废',value:'F'},
            {label:'核对完成',value:'S'},
             {label:'正在核对',value:'W'}
    ]
    // 传入按钮层
    moreData = {
        morebutton: true,
    }
    buttonData = [
        {key: 'merge', value: '核对', if: false },
    ]


    ngOnInit() {
        this.token  = this.tokenService.get().seniortoken;
        this.getData();
        this.getElement();
        this.showAdd = true;

    }
  search:recodeModule = new recodeModule()
    elementScice = [];
    getElement() {
        this.utilityService.getData(appConfig.testUrl  + appConfig.API.sProfiles)
            .subscribe(
                (val) => {
                    this.elementScice = val.result;
                    console.log(val)
                }, (error) => {
                    this.nznot.create('error', error.code,  error.msg);
                }
            );
    }

    getData(type?) {
        if (type === 'search') {
            this.pageIndex = 1;
        }
        const page = {
            condition: this.search,
            page : {
                size: 10,
                current : this.pageIndex,
                orderByField: 'guid',
                asc: false
            }
        };
   this.listloading = true;
        this.utilityService.postData(appConfig.testUrl  + appConfig.API.checklist, page)
            .subscribe(
                (val) => {
                    this.listloading = false;
                    this.data = val.result.records;

                    this.total = val.result.total; // 总数
                    this.pageTotal = val.result.pages * 10; // 页码

                    for ( let i = 0; i < this.data.length; i++) {
                        this.data[i].checkDate = moment(this.data[i].checkDate).format('YYYY-MM-DD');
                       this.data[i].guidProfiles =  this.data[i].guidProfiles.target;
                       this.data[i].buttonData = this.buttonData;
                    }

                },(error)=>{
                        this.listloading = false;
                       this.nznot.create('error', error.code,  error.msg);
                }
            );
    }

    // 列表组件传过来的内容
    addHandler(event) {
        if (event === 'merge') {
        } else if (event === 'checking') {
            this.modalVisible = true; // 打开核对弹出框
        } else if (event === 'export') {
            this.isVisible = true;
        } else {
        }
    }
    reset(){
         this.search = new  recodeModule();
          this.getData('search');
    }

    // 列表传入的翻页数据
    monitorHandler(event) {

      this.pageIndex = event
         this.getData();

    }

    // 接受子组件删除的数据 单条还是多条
    deleatData(event) {

    }
 // 级联数组
   initOptions=[];
   isWorkitem ={
       'disable':false,
       'title':'请选择工作项及工程名'
   }
   addPatchType = []

    buttonEvent(event) {

        this.mergeId = event.guid;
       if (event.names.key === 'merge') {

         this.isNow = false;
          this.initOptions = []

          this.idcheck = event.guid;
              let index = '';
              let indexs = '';
             this.detailVisible = true;
              this.checkloading = true;
                 this.utilityService.getData( appConfig.testUrl + '/checks/ ' + event.guid)
                     .subscribe(val => { // 改成并行，把后台数据保存，同时去请求菜单，然后把请求的值带到下一个流
                    this.twon = val; // 把后台给的值保存
                     console.log(val.result.deliveryDetails)
                          this.checkloading = false;
                          this.detailVisible = true;
                          if (val.result.check.checkStatus === '正在核对') {
                                this.checkStatus = true;
                          }else {
                               this.title = val.result.check.checkStatus
                                this.checkStatus = false;
                          }
                           let icon= ''
                           let color =''
                           let disabledS:boolean
                           if(val.result.deliveryDetails.length == 0){
                               this.isWorkitem.disable = true;
                               this.isWorkitem.title = '暂无数据'
                               let obj = {
                                    'value':'',
                                    'label':'暂无数据',
                                    'disable':true
                                     }
                              this.initOptions.push(obj)
                           }else{
                             this.isWorkitem.title = '请选择工作项及工程名'
                             this.isWorkitem.disable = false;
                            for(let i =0;i<val.result.deliveryDetails.length;i++){


                                this.deliveryResults.forEach(x=>{
                                    if(x.value == val.result.deliveryDetails[i].delivery.deliveryResult){
                                        color = x.color;
                                        icon = x.icon
                                    }
                                })

                                if (  val.result.deliveryDetails[i].delivery.deliveryResult === '核对中' ){
                                            disabledS = false;
                                            }else {
                                            disabledS= true;
                                        }
                                let obj = {
                                    'value':val.result.deliveryDetails[i].delivery.guid,
                                    'label':val.result.deliveryDetails[i].delivery.guidWorkitem.target,
                                    'deliveryResult':val.result.deliveryDetails[i].delivery.deliveryResult,
                                    'deliveryTime':val.result.deliveryDetails[i].delivery.deliveryTime,
                                    'profiles':val.result.deliveryDetails[i].delivery.guidProfiles.target,
                                    'proposer':val.result.deliveryDetails[i].delivery.proposer,
                                    'disabledS':'',
                                    'checkingloading':false,
                                    'icon':icon,
                                    'color':color,
                                    'disable':false
                                }
                                this.initOptions.push(obj)
                            }
                          }


                }
                   , (error) => {
                                   this.nznot.create('error', error.code,  error.msg);
                                })

               this.getMergeList();



2
        }



    }
    getMergeList(){
      const page = {
            page : {
                size: 10,
                current : this.YpageIndex,
                asc: false
            }
        };

                let url = '/checks/'+this.mergeId+'/checkList/merge/list'
                   let index = '';
              let indexs = '';
          this.utilityService.postData(appConfig.testUrl  + url, page)
                    .subscribe(menu => {
                        this.YpageTotal = menu.result.total;
                         this.mergeListData  = menu.result.records;
                          let star = '';
                          let end = '';
                        for  (let i = 0; i < this.mergeListData.length; i ++) {
                            switch(this.mergeListData[i].confirmStatus){
                                case '加入投放':
                                 this.mergeListData[i]['checkbuttons'] = true;
                                 break;
                                  case '删除':
                                 this.mergeListData[i]['checkbuttons'] = false;
                                 break;
                                  default :
                                 this.mergeListData[i]['checkbuttons'] = null;
                                 break;
                            }

                            if (this.mergeListData[i].fullPath) {
                                indexs = this.mergeListData[i].fullPath.indexOf(this.mergeListData[i].partOfProject);
                                this.mergeListData[i].fullPath = this.mergeListData[i].fullPath.substring(indexs, this.mergeListData[i].fullPath.length);
                                                  if(this.mergeListData[i].fullPath.length > 30){
                                                        star = this.mergeListData[i].fullPath.substr(0, 10)
                                                        end = this.mergeListData[i].fullPath.substr(this.mergeListData[i].fullPath.length - 20)
                                                           this.mergeListData[i].fullPathstr = star + '...' + end;
                                                        }else {
                                                            this.mergeListData[i].fullPathstr = this.mergeListData[i].fullPath;
                                                     }
                         }
                           if (this.mergeListData[i].programName.length > 40){
                                                        star = this.mergeListData[i].programName.substr(0, 10)
                                                        end = this.mergeListData[i].programName.substr(this.mergeListData[i].programName.length - 10)
                                                           this.mergeListData[i].programNamestr = star + '...' + end;
                                                        }else{
                                                            this.mergeListData[i].programNamestr = this.mergeListData[i].programName;
                                                     }
                        }
                console.log(this.mergeListData)

                    }
                     ,
                (error) => {

                   this.nznot.create('error', error.code,  error.msg);
                })
    }

    isSpinning = false;
    loginData:any;
    twon :any;
    deliveryPatchDetails ={
        'fileList':[],
        'projectName':'',
        'patchType':'',
        'deployWhere':''
    };
    two = [];
    isNow= false;
        selected(event){
               console.log(event)

             let star = '';
                let end = '';
              let index = '';
              let indexs = '';
            this.isSpinning = true;
              this.utilityService.getData( appConfig.testUrl + '/checks/' +this.mergeId+'/checkList/delivery/'+event.value+'/list')
                         .subscribe(
                         (val) => {
                               this.isWorkitem.title=event.label
                             this.isNow = true
                             this.isSpinning = false;
                             this.checkModalData = val.result;
                             console.log(this.checkModalData)
                                for  (let i = 0; i < this.checkModalData.length; i ++) {
                                for (let x = 0; x < this.checkModalData[i].deliveryPatchDetails.length; x ++) {

                                    for (let  y = 0; y < this.checkModalData[i].deliveryPatchDetails[x].fileList.length; y ++) {

                                         switch(this.checkModalData[i].deliveryPatchDetails[x].fileList[y].confirmStatus){
                                                case '已合并':
                                                this.checkModalData[i].deliveryPatchDetails[x].fileList[y]['buttons'] = true;
                                                break;
                                                 case '不投放':
                                                this.checkModalData[i].deliveryPatchDetails[x].fileList[y]['buttons'] = false;
                                                break;
                                                default:
                                                this.checkModalData[i].deliveryPatchDetails[x].fileList[y]['buttons'] = null
                                         }
                                        if (this.checkModalData[i].deliveryPatchDetails[x].fileList[y].fullPath) {
                                            index = this.checkModalData[i].deliveryPatchDetails[x].fileList[y].fullPath.indexOf(this.checkModalData[i].projectName);
                                            this.checkModalData[i].deliveryPatchDetails[x].fileList[y].fullPath = this.checkModalData[i].deliveryPatchDetails[x].fileList[y].fullPath.substring(index, this.checkModalData[i].deliveryPatchDetails[x].fileList[y].fullPath.length);
                                              if(this.checkModalData[i].deliveryPatchDetails[x].fileList[y].fullPath.length > 40) {
                                                        star = this.checkModalData[i].deliveryPatchDetails[x].fileList[y].fullPath.substr(0, 15)
                                                        end = this.checkModalData[i].deliveryPatchDetails[x].fileList[y].fullPath.substr(this.checkModalData[i].deliveryPatchDetails[x].fileList[y].fullPath.length - 15)
                                                            this.checkModalData[i].deliveryPatchDetails[x].fileList[y].fullPathstr = star + '...' + end;
                                                        }else{
                                                           this.checkModalData[i].deliveryPatchDetails[x].fileList[y].fullPathstr = this.checkModalData[i].deliveryPatchDetails[x].fileList[y].fullPath;
                                                     }

                              }
                                    }
                                }
                            }

                 } ,
                (error) => {

                   this.nznot.create('error', error.code,  error.msg);
                })

        }






// }
 titlestr = '完成此项操作吗？'
    status:string;
    mergeClick(index) {
          this.isOkLoading = false;
        switch (index) {
            case 0 :
                this.detailVisible = false
                return;
            case 1 :
                this.status  = 'F'
                this.titlestr = '作废核对'
                this.isVisibleSuccess = true
                break;
            case 2 :

                this.status = 'S'
                this.titlestr = '完成核对'
                this.isVisibleSuccess = true
                break;
        }
    }
    isVisibleSuccess = false;
    isOkLoading = false;

    handleOkSuccess(){
     this. isOkLoading = true;
     this.utilityService.putData( appConfig.testUrl + '/checks/' + this.mergeId + '/status/' + this.status, {})
                    .subscribe(
                        (val) => {

                            if (val.code === '200') {
                                this.nznot.create('success', val.msg,  '');
                                this.isVisibleSuccess =false;
                                this. isOkLoading = false;
                                this.detailVisible = false;
                                this.getData();
                            }else {
                                this.nznot.create('error', val.code, val.msg);
                            }
                        },(error) => {
                             this. isOkLoading = false;
                            this.isVisibleSuccess =false;
                           this.nznot.create('error', error.code,  error.msg);
                        })
    }

    // 列表按钮方法
    buttonDataHandler(event) {
    }
    chancanle(event){
        console.log(event)
            console.log(  this.iStouchanRecord)
         this.iStouchanRecord = false;
    }
     checkboxPatch(event){
        let i = event.i;
        let status =event.status
            i.checked = status

            this.addPatchType.forEach(x=>{
            if( this.isPro ==='S'|| this.isPro ==='I'){
                 if(i.exportType !== x.exportType){
                       x.checked = false

                 }
                }
                //  if(!x.checked){
                     x.children.forEach((j,index)=>{
                           j.checked = x.checked

                         if( this.isPro ==='S' && x.checked ){
                             console.log(index)
                                if( index === 0){
                                        j.checked = x.checked
                                }else{
                                    j.checked  = false
                                }
                         }


                      if( i.children.length===1){
                            j.disabled = true
                        }else{
                            if(this.isPro ==='P'||this.isPro ==='C'){
                                 j.disabled = true
                            }else{
                                  j.disabled = false
                            }
                        }




              })
                // }


            })


         console.log(i)
  }
    checkboxChild(event){
        let s=event.s;
        let i = event.i;
        let status =event.status
        s.checked = status
      let arr = []

      i.children.forEach(index=>{

             if(s.name === index.name){
                  index = s
             }
             if(index.checked){
                   arr.push(index)
             }

      })
      let obj=true;
      if(arr.length === 1){
            obj = true
        }else{
            obj = false
         }

      i.children.forEach(index=>{
           if( this.isPro ==='S'){
                  if(index.name === s.name){
                        index.checked = status
                 }else{
                      index.checked = false
                 }
              }
          if(index.checked){
                  index.disabled = obj
          }

            })
    }
    isPro:string
    guidCheckList:string;// 核对代码的guid
    Deliveryguid:string;//  申请guid
    buttonClick(event){

            let type = event.index;
            this.guidCheckList = event.id.guid;
            let soyin = event.soyin;
            this.addPatchType = []
            console.log(event)
            if (type === 4) {

             this.utilityService.getData( appConfig.testUrl + '/checks/'+ this.guidCheckList+'/pathPatchDeploy')
                         .subscribe(
                         (val) => {
                           console.log(val)
                             val.result.patchDeploy = JSON.parse(val.result.patchDeploy)
                             val.result.patchDeploy.forEach(i=>{
                                 i.deployType = i.deployType.split(',')
                             })
                             let childDisabl;
                             let disabl;
                             let check = true;

                             this.isPro = val.result.projectType
                              switch(val.result.projectType){
                                      case 'S':
                                      childDisabl = false
                                      disabl = false;
                                      break;
                                      case 'I':
                                      childDisabl = false
                                      disabl = false;
                                      break;
                                       case 'C':
                                      childDisabl = true
                                      disabl = false;
                                      break;
                                      default:
                                      childDisabl = true
                                      disabl = true;
                                      break;
                                    }

                                    if(val.result.patchDeploy.length === 1){
                                        disabl = true
                                    }

                                   val.result.patchDeploy.forEach((j,index)=>{
                                          j.checked = check;
                                        if(val.result.projectType === 'I' || val.result.projectType === 'S'){
                                            if(index===0){
                                                  j.checked = check;
                                            }else{
                                                  j.checked = false;
                                            }

                                        }

                                        j.disabled = disabl;
                                        j.children = []

                                     if(j.deployType.length ===1){
                                              childDisabl = true
                                     }
                                     let flage = true;
                                        j.deployType.forEach((l,it)=>{
                                            if(j.checked){
                                                if(val.result.projectType === 'S' ){
                                                    if(it === 0 ){
                                                     flage = true
                                                }else{
                                                      flage = false
                                                }
                                                }
                                                   j.children.push({name:l,checked:flage,disabled:childDisabl})
                                            }else{
                                                  j.children.push({name:l,checked:false,disabled:childDisabl})
                                            }


                                        })
                                    })
                                     this.addPatchType =  val.result.patchDeploy
                                       this.iStouchanRecord = true;
                                   console.log( this.addPatchType )
                         },(error)=>{
                               this.nznot.create('error', error.code,  error.msg);
                         })


            }else {
              this.utilityService.putData( appConfig.testUrl + '/checkLists/' +  this.guidCheckList + '/status/' + type, {})
                         .subscribe(
                         (val) => {
                          if (val.code === '200') {

                           this.nznot.create('success', val.msg, '');
                           this.iStouchanRecord = false;

                           if (type === 3) {
                             event.id.confirmStatus='删除'
                             event.id.checkbuttons = false;
                           }
                          }
                         }, (error) => {

                         this.nznot.create('error', error.code,  error.msg);

                         });
                          }
            }

    // 处理行为代码，跳转、弹出框、其他交互
    isActive(event) {

    }


    selectedRow(event) { // 选中方法，折叠层按钮显示方法

    }

   DopageNumber(event){
           console.log(event)
       this.YpageIndex = event
       this.getMergeList();

   }



    // 比对界面
    checkVisible = false; // 默认是关闭的

    // 核对清单弹框
    environment = [
        { text: 'SIT', value: false, key: 'SIT' },
        { text: 'SIT Dev', value: false, key: 'Dev' },
        { text: 'UAT', value: false, key: 'UAT' }
    ]


    save() {
        this.modalVisible = false; // 关闭选择框
        this.checkVisible = true; // 打开核对弹出框
    }


    // 状态
    returns() {

    }

    sussess() {

    }

    errors() {

    }

      guidDelivery: string;
      patchType: any;
      deployWhere: any;
    // 关闭核对清单
    checkSave(event) {
     let objs = event.arr
     let obj ={

            deployConfig: event.arr,
            guidCheckList:this.guidCheckList,// 核对代码的guid
            guidDelivery:event.guidDelivery//  申请guid
        }
     this.utilityService.putData( appConfig.testUrl + '/checkLists/' + event.errorId + '/delivery', obj)
                         .subscribe(
                         (val) => {
                          if (val.code === '200') {
                                 this.iStouchanRecord = false;
                             this.mergeListData.forEach((result,i) => {
                                 if(result.guid === event.errorId){
                                     this.mergeListData[i].checkbuttons = true;
                                       this.mergeListData[i].confirmStatus = '加入投放';
                                       this.mergeListData[i].patchType = event.patchType
                                 }
                             })

                           this.nznot.create('success', val.msg, '');
                          }
                         }, (error) => {
                                this.nznot.create('error', error.code,  error.msg);
                         });
    }


    // 打印界面
    isVisible = false; // 默认关闭
    workItem = false;

    checkOptionsOne  = [
        { label: 'TWS改版', value: 'TWS' },
        { label: '1618 国际结算', value: '1618' },
        { label: '无纸化',  value: 'wu' }
    ]


    handleOk() {
        // 请求数据 下载下来
        this.isVisible = false; // 关闭弹出框
    }

    istextVisible = false;
    inputValue: any;
    guid: any;
   returnsclick(event) {
       console.log(event)
       let item = event.index
       this.guid = event.it.value
       let S = '';

       if (item === 1) {

           S = 'S';
       }else {

           S = 'F';
       }
         let  url = appConfig.testUrl + '/checks/delivery/' + this.guid + '/result';
       const obj = {
               result : S,
               desc : this.inputValue
       };
       this.utilityService.putData( url, obj)
           .subscribe(
               (val) => {

                   if (val.code === '200') {
                       this.istextVisible = false;
                       if (item === 1 ) {
                           event.it.disabledS = true
                           event.it.deliveryResult = '核对成功';
                           event.it.color = '#8310e9'
                             event.it.icon = 'anticon-exclamation-circle-o'
                       }else  if (item === 2 ){
                           event.it.disabledS = true
                           event.it.deliveryResult = '申请失败';
                           event.it.color = '#f04134'
                           event.it.icon = 'anticon-close-circle-o'
                       }
                       this.getData()
                       this.nznot.create('success', val.code, val.msg);
                   }else{
                         this.nznot.create('error', val.code, val.msg);
                  }

               }
               ,
               (error) => {
               this.nznot.create('error', error.code,  error.msg);
               }
           );



    }
    // 合并的确定
    determine() {
        this.mergeVisible = false;
    }


}
